package com.astrofizzbizz.stoneedgegui.utilities;

import java.net.*;

import com.jcraft.jsch.JSchException;
import com.sun.image.codec.jpeg.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class AxisCamera2  extends JPanel implements Runnable
{
	private static final long serialVersionUID = 3013569971119551146L;
	private boolean useMJPGStream = true; //still image set to false
	private String jpgURL="http://localhost:8082/axis-cgi/jpg/image.cgi?resolution=352x288";
    private String mjpgURL; //="http://localhost:8082/mjpg/video.mjpg";//"http://192.168.1.198/mjpg/video.mjpg";
    private DataInputStream dis;
    private BufferedImage image=null;
 
    private boolean connected = false;
    private boolean initCompleted = false;
    private boolean imageDrawn = false;
    private HttpURLConnection huc=null;
    private InputStream inputStream = null;
    private BufferedInputStream bufferedInputStream = null;
 
    private JEditorPane  jEditorPane = new JEditorPane();
    private String httpUrlLead = "";

    private JLabel imageIconLabel = new JLabel();


    /** Creates a new instance of AxisCamera1 */
    public AxisCamera2(String host, int port, int cameraWidth, int cameraHeight) 
    {
    	mjpgURL = "http://" + host + ":" + (new Integer(port).toString()) + "/mjpg/video.mjpg";
    	
    	httpUrlLead = "http://" + host + ":" + (new Integer(port).toString());
    	Dimension dim = new Dimension(cameraWidth, cameraHeight);
		setPreferredSize(dim);
		setMinimumSize(dim);
		setMaximumSize(dim);
		setSize(dim);
		
		setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLUE, 4),BorderFactory.createEmptyBorder(5,5,5,5)));
		add(imageIconLabel, BorderLayout.CENTER);
   }
 
	public void connect()
    {
        try
        {
            URL u = new URL(useMJPGStream?mjpgURL:jpgURL);
            huc = (HttpURLConnection) u.openConnection();
            inputStream = huc.getInputStream();
            connected = true;
            bufferedInputStream = new BufferedInputStream(inputStream);
            dis= new DataInputStream(bufferedInputStream);
            if (!initCompleted) initDisplay();
        }
        catch(IOException e)
        { //incase no connection exists wait and try again, instead of printing the error
 
            try
            {
                huc.disconnect();
                Thread.sleep(1000);
            }
            catch(InterruptedException ie)
            {
                //huc.disconnect();connect();
            }
            //connect();
        }
        catch(Exception e){;}
    }
 
    public void initDisplay()
    { //setup the display
        if (useMJPGStream)readMJPGStream();
        else
        {
            readJPG();
            disconnect();
        }
        initCompleted = true;
    }
 
    public void disconnect()
    {
	    try
	    {
	    	if(connected)
	    	{
	    		connected = false;
	    	    try {Thread.sleep(200);} catch (InterruptedException e) {;}
	    		dis.close();
	    		bufferedInputStream.close();
	    		inputStream.close();
	    		huc.disconnect();
	    	}
	    }
	    catch(Exception e){;}
    }
  
    public void readStream()
    { //the basic method to continuously read the stream
		if (!connected) return;
    	try
    	{
    		if (useMJPGStream)
    		{
			    while(true)
			    {
			    	if (!connected) return;
				    readMJPGStream();
				    if (!imageDrawn) 
				    {
				    	imageDrawn = true;
				    }
				 	imageIconLabel.setIcon(new ImageIcon(image));

			    }
			}
    	}
    	catch(Exception e){;}
    }
 
 
    public void readMJPGStream()
    { //preprocess the mjpg stream to remove the mjpg encapsulation
    	if (!connected) return;
	    readLine(4,dis); //discard the first 3 lines
	    readJPG();
	    readLine(1,dis); //discard the last two lines
    }
 
    public void readJPG()
    { //read the embedded jpeg image
    	if (!connected) return;
    	try
    	{
        	if (!connected) return;
		    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(dis);
		    image = decoder.decodeAsBufferedImage();
		 
//		    String s="a"+counter+".jpg";
//		    counter++;
//		    String filename="c:\\find_stillset\\"+s;
		 
//		    BufferedImage smaller = toBufferedImage(getScaledInstanceAWT(image, 1.0/3.0));//scalling image size
		}
    	catch(Exception e){/* e.printStackTrace(); */disconnect();}
	}
    public void readLine(int n, DataInputStream dis)
    { //used to strip out the header lines
    	if (!connected) return;
	    for (int i=0; i<n;i++)
	    {
	    	if (!connected) return;
	    	readLine(dis);
	    }
    }
 
    public void readLine(DataInputStream dis)
    {
    	if (!connected) return;
	    try
	    {
		    boolean end = false;
		    String lineEnd = "\n"; //assumes that the end of the line is marked with this
		    byte[] lineEndBytes = lineEnd.getBytes();
		    byte[] byteBuf = new byte[lineEndBytes.length];
		 
		    while(!end)
		    {
		    	if (!connected) return;
			    dis.read(byteBuf,0,lineEndBytes.length);
			    String t = new String(byteBuf);
			    if(t.equals(lineEnd)) end=true;
		    }
	    }
//	    catch(Exception e){e.printStackTrace();}
	    catch(Exception e){;}
    }
    public void run() 
    {
        connect();
        readStream();
    }
	public void moveCamera(String direction)
	{
		String urltemp = httpUrlLead +  "/axis-cgi/com/ptz.cgi?camera=1&rzoom=0";
		String url = httpUrlLead + "/axis-cgi/com/ptz.cgi?camera=1&";
		if (direction.equals("up")) url = url + "move=up";
		if (direction.equals("down")) url = url + "move=down";
		if (direction.equals("left")) url = url + "move=left";
		if (direction.equals("right")) url = url + "move=right";
		if (direction.equals("zoomIn")) url = url + "rzoom=100";
		if (direction.equals("ZoomOut")) url = url + "rzoom=-100";
		try 
		{
			System.out.println("Moving camera...\n" + url);
			jEditorPane.setPage(url);
			try {Thread.sleep(300);} catch (InterruptedException e) {;}
			jEditorPane.setPage(urltemp);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
    public boolean isImageDrawn() {return imageDrawn;}

	public static void main(String[] args) throws InterruptedException, JSchException 
    {
	 
    	String hostname;
    	int port;
		int cameraWidth = 720;
		int cameraHeight = 520;
        
/*	    String host = "mail.stoneedgevineyard.com";
	    String user = "remote";
	    String tunnelP = "Zebo!@graf";
	    StoneEdgeIIITunnel stoneEdgeIIITunnel = new StoneEdgeIIITunnel(host, user, tunnelP);	
	    stoneEdgeIIITunnel.setPortForwarding(8080, "localhost", 8080);
	    stoneEdgeIIITunnel.setPortForwarding(8081, "localhost", 80);
	    stoneEdgeIIITunnel.setPortForwarding(8082, "axis", 80);
	    stoneEdgeIIITunnel.setPortForwarding(8083, "axis1", 80);
	    hostname = "localhost";
	    port = 8082;
*/	    
	    hostname = "192.203.224.2";
	    port = 8090;
		cameraWidth = 840;
		cameraHeight = 660;
	    
	    JFrame jframe = new JFrame("Lake Geneva WebCam");
        try 
        {
            UIManager.setLookAndFeel(
            UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {}
	    
	    System.out.println("Connected...");
	    AxisCamera2 axisCameraPanel = new AxisCamera2(hostname, port, cameraWidth, cameraHeight);
	    Thread axisCamera1Thread = new Thread(axisCameraPanel);
	    axisCamera1Thread.start();
		jframe.getContentPane().add(axisCameraPanel);
//		jframe.pack();
		jframe.setVisible(true);
		jframe.setSize(new Dimension(cameraWidth,cameraHeight));
		jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


}
